import merged from 'obj-merged';
import * as config from '../Config/Config';
import { stringify } from 'qs';
import decode from './urlencode.min'
const {target} = config;
const Tool = {};
/**
 * 缓存请求
 *
 * @param{any}
 * @returns
 */

Tool.createFetch = function (obj) {
    return function(params){
        let initObj = {
            initBase:'https://data.api.ppkao.com',
            initParam:{

            }
        }
        let arr = Object.keys(obj);
        arr.forEach((val,ind)=>{
            initObj[val] = obj[val]
        })

        fetch(initObj + obj.url + stringify(initObj.initParam))
            .then(response => response.json())
            .then(response => decode(response))
            .then(response => {

            })
            .catch( err => {
                console.error(err);
            })
    }
}


/**
 * 格式化时间
 *
 * @param {any}
 * @returns
 */
Tool.formatDate = function (str) {
    var date = new Date(str);
    var time = new Date().getTime() - date.getTime(); //现在的时间-传入的时间 = 相差的时间（单位 = 毫秒）
    if (time < 0) {
        return '';
    } else if (time / 1000 < 60) {
        return '刚刚';
    } else if ((time / 60000) < 60) {
        return parseInt((time / 60000)) + '分钟前';
    } else if ((time / 3600000) < 24) {
        return parseInt(time / 3600000) + '小时前';
    } else if ((time / 86400000) < 31) {
        return parseInt(time / 86400000) + '天前';
    } else if ((time / 2592000000) < 12) {
        return parseInt(time / 2592000000) + '月前';
    } else {
        return parseInt(time / 31536000000) + '年前';
    }
}

/**
 * 本地数据存储或读取
 *
 * @param {any} key
 * @param {any} value
 * @returns
 */
Tool.localItem = function (key, value) {
    if (arguments.length == 1) {
        return localStorage.getItem(key);
    } else {
        return localStorage.setItem(key, value);
    }
}

/**
 * 删除本地数据
 *
 * @param {any} key
 * @returns
 */
Tool.removeLocalItem = function (key) {
    if (key) {
        return localStorage.removeItem(key);
    }
    return localStorage.removeItem();
}

export { Tool, merged, config }